﻿using System;
using System.IO;
using System.Text;
using System.Xml.Linq;

namespace XmlDatabase.Core
{
    internal class XLogWriter : TextWriter
    {
        public override Encoding Encoding => Encoding.UTF8;

        private XDatabase db;
        private XDocument doc;
        private String logFile;

        internal XLogWriter(XDatabase database)
        {
            this.db = database;
            String str1 = Path.Combine(this.db.FullName, "SystemLogs");
            String str2 = DateTime.Now.ToString("yyyy-MM-dd");
            this.logFile = Path.Combine(str1, String.Format("{0}.xml", str2 ));
            Directory.CreateDirectory(str1);
            if (!File.Exists(this.logFile))
            {
                this.doc = new XDocument(new Object[1]
                {
                 new XElement("XMLDatabase-SystemLogs",new Object[2]{
                 new XAttribute("Date",str2 ),
                 new XAttribute("EngineVersion",this.db.Version )})
                });
                this.doc.Save(this.logFile);
            }
            else
            {
                this.doc = XDocument.Load(this.logFile);
            }
        }
        public override void Write(String value)
        {
            this.WriteLine(value);
        }
        public override void WriteLine(String value)
        {
            this.doc.Root.Add(new XElement("LogEntry", new Object[4]{
                new XAttribute("Time",DateTime.Now ),
                new XAttribute("Message",value ),
                new XAttribute("Application",this.db.ApplicationName),
                new XAttribute("UserName",this.db.UserName)
              }));
        }
        public override void Flush()
        {
            this.doc.Save(this.logFile);
        }
        public override void Close()
        {
            this.Flush();
        }
    }
}
